<!--
	时间：2020-12-10
	描述：对账明细汇总统计报表
-->

<!--<template>-->
<template>
  <div class="m-view-goodsAccountBill2 m-window">
    <!--查询条件-->
    <div class="m-condition">
      <el-row :gutter="10">
        <el-form
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
         <el-col :span="7">
            <el-form-item :label="permission==4?'客户':'公司'" class="rightItem">
              <el-select
                value-key="id"
                ref="content"
                v-model="searchForm.companyCode"
                :placeholder="`请选择${permission==4?'客户':'公司'}`"
                @change="companyChange"
                filterable
                clearable
              >
                <el-option
                  v-for="item in comOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.companyCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="入库日期" class="rightItem">
              <el-date-picker
                v-model="searchForm.instockDateStart"
                type="date"
                placeholder="入库开始日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="searchForm.instockDateEnd"
              type="date"
              ref="endPicker"
              @focus="endDateFocus"
              placeholder="入库结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerEndOptions"
            ></el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-form-item label="采购订单" class="rightItem">
                <el-input
                v-model="searchForm.purOrdNo"
                placeholder="请输入采购订单号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库单号" class="rightItem">
              <el-input
                v-model="searchForm.instockNo"
                placeholder="请输入入库单号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row :gutter="10">
        <el-form
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
        <el-col :span="7" v-if="permission==1">
            <el-form-item label="供应商" class="rightItem">
              <el-input
                placeholder="请选择供应商"
                v-model="selCusName"
                clearable
                @focus="showSupplierDialog"
                readonly
                @mouseenter.native="mouseEnter"
                @mouseleave.native="mounseLeave"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="showSupplierDialog"
                ></el-button>
                <span
                  slot="suffix"
                  @click="inputClearSon"
                  class="m-cleanInput"
                  v-show="inputClearBut"
                >
                  <i
                    class="el-input_icon el-icon-circle-close el-input__clear"
                  ></i>
                </span>
              </el-input>
            </el-form-item>
        </el-col>
        <el-col :span="permission==4?7:5">
            <el-form-item label="物料描述" class="rightItem">
              <el-input
                v-model="searchForm.matName"
                placeholder="请输入物料描述"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        <el-col :span="permission==4?5:4">
            <el-form-item label="送货单号" class="rightItem">
              <el-input
                v-model="searchForm.deliveryNo"
                placeholder="请输入送货单号"
                clearable
              ></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="4">
            <el-form-item label="物料编码" class="rightItem">
              <el-input
                v-model="searchForm.matCode"
                placeholder="请输入物料编码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="2" class="m-floatRight">
          <el-button type="primary" @click="searchReport(1)">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <!--采购订单跟踪列表-->
    <div
      class="m-agTable m-bottom m-top2"
      v-loading="loading"
    >
      <agGridComponents
        ref="reportGridComponent"
        :getGridOptions="reportGridOptions"
        :getColumnDefs="reportColumnDefs"
        :getRowSelection="reportRowSelection"
        :isColFit="isColFit"
      ></agGridComponents>
    </div>
    <!-- 分页 -->
    <div class="m-page">
      <el-pagination
        @size-change="reportHandleSizeChange"
        @current-change="reportHandleCurrentChange"
        :current-page="pageInfo.current"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      ></el-pagination>
    </div>
    <!-- 供应商弹窗 -->
    <el-dialog
      title="供应商信息"
      :visible.sync="srmSupplierDialogVisible"
      width="50%"
      :before-close="srmSupplierDialogClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <srmSupplierInfo
        ref="srmSupplierInfo"
        :layout="layout"
        @setSrmSupplierInfo="setSrmSupplierInfo"
      ></srmSupplierInfo>
    </el-dialog>
  </div>
</template>

<script>
import _Api from '@/api';
import localeText from '@/i18n/agGridText';
import { formatPrice } from '@/util/format';
import agGridComponents from '@/components/agGridComponents.js';
import Msg from '@/public/message';
import srmSupplierInfo from '@/components/srmSupplierInfo.vue';
/**
 * @group purchaseReport
 * 入库明细查询
*/
export default {
  data() {
    return {
        // vuese
        // 查询参数
        searchForm: {
            instockNo: '',
            matName: '',
            instockDateEnd: '',
            instockDateStart: '',
            purOrdNo: '',
            deliveryNo:'',
            matCode:'',
            companyCode:''
        },
        //   vuese
        //   表格配置
        reportGridOptions: '',
        //   vuese
        // 表格列配置
        reportColumnDefs: [],
        //   vuese
        // 设置表格多选
        reportRowSelection: 'multiple',
        //   vuese
        // 分页相关配置
        pageInfo:{
            size:30,
            current:1,
            total:0
        },
        isColFit: true,
        loading: false,
        rowData: [],
        //  vuese
        // 结束日期选项配置
        pickerEndOptions: this.endStartOptions(),
        permission:'',
        //   vuese
        // 公司列表
        comOptions: [],
        //   vuese
        // 供应商弹窗的可见性
        srmSupplierDialogVisible: false, 
        //   vuese
        // 供应商弹窗配置
        layout: {},
        //   vuese
        // 选择的供应商名称
        selCusName: '',
        //   vuese
        // 选择的供应商编码
        selCusCode: '',
        //   vuese
        // 是否显示清除按钮
        inputClearBut: false,
    };
  },
  created() {
      this.permission = this.$global.user.userTypeId
  },
  beforeMount() {
    //   表格配置
    this.reportGridOptions = {
      context: {
        componentParent: this,
      },
      rowSelection: 'single',
      enableColResize: true,
      localeText: localeText,
      suppressRowClickSelection: true,
    };

    this.isColFit = true;
    // 行配置
    this.reportColumnDefs = [
      { headerName: '采购订单号', field: 'purOrdNo', width: 120 },
      { headerName: '行项目号', field: 'purOrdMxNo', width: 100 },
      { headerName: '物料编号', field: 'matCode', width: 120 },
      { headerName: '物料描述', field: 'matName', width: 260 },
      { 
          headerName: this.permission==1?'公司':'客户', 
          field: 'companyName', 
          width: 160,
      },
      { headerName: '供应商', field: 'supplierName', width: 160,hide:this.permission==4 },
      { headerName: '入库单号', field: 'instockNo', width: 100 },
      { headerName: '入库行号', field: 'instockMxNo', width: 100 },
      {
        headerName: '入库日期',
        field: 'instockDate',
        width: 120,
        valueFormatter: (params) => {
          if (params.value) {
            return params.value.substr(0, 10);
          } else {
            return '';
          }
        },
      },
      { 
          headerName: '数量',
          field: 'instockAmount', 
          width: 120,
          valueFormatter:(params)=>{
              if(params.value){
                  return formatPrice(params.value)
              }
          }
      },
      { headerName: '单位',field: 'unitCode', width: 80,},
      { 
          headerName: '价格数量',
          field: 'priceAmount',
          width: 120,
          valueFormatter:(params)=>{
              if(params.value){
                  return formatPrice(params.value)
              }
          }
      },
      { headerName: '价格单位',field: 'priceUnit', width: 100,},
      { 
          headerName: '借贷', 
          field: 'blFlag', 
          width: 80, 
          valueFormatter:(params)=>{
              if(params.value=='S'){
                  return "正向"
              } else if(params.value=='H'){
                 return "反向"
              }
          }
      },
      { headerName: '移动类型', field: 'moveType', width: 100 },
      { headerName: '备注', field: 'remark', width: 150 },
      { headerName: '送货单号', field: 'deliveryNo', width: 120 },
      { headerName: '送货单行号', field: 'deliveryIMxNo', width: 100 },
      { headerName: '内向交货单', field: 'inDeliveryNo', width: 100 },
      { headerName: '内向交货单行号', field: 'inDeliveryMxNo', width: 150 },
    ];
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.reportGridComponent.gridOptions.api.setRowData(this.rowData);
    });
    this.searchForm.instockDateEnd = new Date().Format('yyyy-MM-dd')
    this.searchForm.instockDateStart = new Date(Date.parse(new Date()) - 15*24*60*60*1000).Format('yyyy-MM-dd')
    // this.searchReport(1)
    this.getAuthInfo();
  },
  components: {
    agGridComponents,
    srmSupplierInfo,
  },
  methods: {
    /**
     * @vuese
     * 选择公司名称回调
     * @arg 参数companyCode为公司编码
    */
    companyChange(companyCode) {
      if (this.permission == 1) {
        if (companyCode) {
          this.layout.companyCode = companyCode;
          this.layout.auth = true;
          // this.layout.filterByUser = true;
          if (this.selCusCode) this.selCusCode = '';
          if (this.selCusName) this.selCusName = '';
        } else {
          this.layout = {};
          this.selCusName = '';
          this.selCusCode = '';
        }
      }
      // this.currentPage = 1;
    },
    /**
     * @vuese
     * 打开选择供应商选择弹窗
    */
    showSupplierDialog() {
      if (!this.layout.companyCode) {
        this.$alert('提示：请选择公司！', {
          showClose: false,
          confirmButtonText: '确定',
          customClass: 'alertPrompt',
        });
        this.$refs.content.focus();
        return;
      } else {
        this.srmSupplierDialogVisible = true;
        this.$nextTick((_) => {
          this.$refs.srmSupplierInfo.search();
        });
      }
    },
    /**
     * @vuese
     * 关闭选择供应商弹窗回调
    */
    srmSupplierDialogClose(done) {
      this.$refs.srmSupplierInfo.keyWord = '';
      this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
        this.$refs.srmSupplierInfo.keyWord
      );
      done();
    },
    /**
     * @vuese
     * 输入框清除事件监听
    */
    inputClearSon() {
      this.selCusCode = '';
      this.selCusName = '';
      this.inputClearBut = false;
    },
    /**
     * @vuese
     * 回显选择的供应商信息
    */
    setSrmSupplierInfo(msg) {
      if (msg.length > 0) {
        this.$refs.srmSupplierInfo.keyWord = '';
        this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
            this.$refs.srmSupplierInfo.keyWord
        );
        this.srmSupplierDialogVisible = false;
        this.selCusCode = msg[0].supplierCode;
        this.selCusName = msg[0].supplierName;
      }
    },
    /**
     * @vuese
     * 供应商输入框鼠标移入事件监听
    */
    mouseEnter() {
      if (this.selCusName != '') this.inputClearBut = true;
    },
    /**
     * @vuese
     * 供应商输入框鼠标移出事件监听
    */
    mounseLeave() {
      if (this.selCusName != '') this.inputClearBut = false;
    },
    /**
     * @vuese
     * 结束日期不可选择配置
    */
    endStartOptions() {
      let that = this;
      return {
        disabledDate(time) {
          const { instockDateStart } = that.searchForm;
          let currentDate = new Date(time).getTime();
          if (instockDateStart) {
            let startTime = new Date(`${instockDateStart} 00:00:00`).getTime();
            let days = (currentDate-startTime)/(24*60*60*1000)
            if (currentDate < startTime) {
              return true;
            }  else if(days>90){
              return true
            }else{
              return false;
            }
          }
        },
      };
    },
    /**
     * @vuese
     * 结束日期控件聚焦回调
     */
    endDateFocus() {
      if (!this.searchForm.instockDateStart) {
        Msg.showPopMsg("请先选择开始日期");
        this.$refs["endPicker"].blur();
      }
    },
    /**
     * @vuese
     * 每页显示条数改变回调
     * @arg 参数size当前显示条数
    */
    reportHandleSizeChange(size) {
      this.pageInfo.size = size;
      this.searchReport(1);
    },
    /**
     * @vuese
     * 页码改变回调
     * @arg 参数current当前页码
    */
    reportHandleCurrentChange(current) {
      this.pageInfo.current = current;
      this.searchReport();
    },
    /**
     * @vuese
     * 查询报表数据
     * @arg 参数temp重置页码标识
    */
    searchReport(temp) {
        if(temp)this.pageInfo.current = 1
        if (
          !this.searchForm.purOrdNo &&
          !this.searchForm.instockNo &&
          !this.searchForm.instockDateEnd&&!this.searchForm.instockDateStart
        ) {
          Msg.showPopMsg(
            '采购订单号/入库单号/入库日期任意一项不能为空！'
          );
          return;
        } else {
            if(this.searchForm.instockDateStart||this.searchForm.instockDateEnd){
                if(!this.searchForm.companyCode){
                    Msg.showPopMsg(`请选择${this.permission==1?'公司':'客户'}!`);
                    return;
                }
                if (!this.searchForm.instockDateStart) {
                    Msg.showPopMsg('请选择入库开始日期!');
                    return;
                } else if (!this.searchForm.instockDateEnd) {
                    Msg.showPopMsg('请选择入库结束日期!');
                    return;
                } else if (
                Date.parse(this.searchForm.instockDateEnd) <
                Date.parse(this.searchForm.instockDateStart)
                ) {
                    Msg.showPopMsg('入库结束日期不能早于入库开始日期,请重新选择!');
                    return;   
                } else if((Date.parse(this.searchForm.instockDateEnd)-Date.parse(this.searchForm.instockDateStart))/(24*60*60*1000)>90){
                    Msg.showPopMsg('查询日期范围不可超过90天,请重新选择!');
                    return;  
                }
            }
        }
      let params = {
        ...this.searchForm,
        purOrdNo: this.searchForm.purOrdNo.trim(),
        deliveryNo:this.searchForm.deliveryNo.trim(),
        matCode:this.searchForm.matCode.trim(),
        instockNo: this.searchForm.instockNo.trim(),
        matName: this.searchForm.matName.trim(),
        instockDateEnd: this.searchForm.instockDateEnd
          ? `${this.searchForm.instockDateEnd} 00:00:00`
          : '',
        instockDateStart: this.searchForm.instockDateStart
          ? `${this.searchForm.instockDateStart} 00:00:00`
          : '',
        current: this.pageInfo.current,
        pageSize: this.pageInfo.size,
        supplierCode: this.selCusCode,
      };
      this.loading = true;
      this.$http
        .getInstockBills(params)
        .then(({ data }) => {
          this.loading = false;
          if (data.code == 1) {
            this.$refs.reportGridComponent.gridOptions.api.setRowData(
              data.rows
            );
            this.pageInfo.total = data.total
            this.rowData = data.rows;
          } else {
            Msg.showErrorMsg(data.info);
          }
        })
        .catch((err) => {
          this.loading = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    /**
     * @vuese
     * 获取当前账号权限公司
    */
    getAuthInfo() {
      //获取当前账号权限公司
      let obj = {};
      //帐号类型：4为供应商
      if (this.$global.user.userTypeId == 4) {
        obj.account = this.$global.user.userName;
        obj.userType = 2;
        this.alertMessage = '请选择客户！';
        this.selCusCode = this.$global.supplierData.supplierCode; //设置默认供应商编码
      }
      //帐号类型：1为内部员工
      else if (this.$global.user.userTypeId == 1) {
        obj.account = this.$global.user.oaNum;
        obj.userType = 1;
        this.alertMessage = '请先选择公司!';
      }
      this.comOptions = [];
      _Api
        .getAuthInfo(obj)
        .then((response) => {
          let data = response.data;
          if (data.code == 1) {
            //绑定公司选项
            if (
              Array.isArray(data.rows.myMstCompany) &&
              data.rows.myMstCompany.length > 0
            ) {
              this.comOptions = data.rows.myMstCompany;
              this.searchForm.companyCode = this.comOptions[0].companyCode;
              this.layout.companyCode = this.comOptions[0].companyCode;
              this.layout.auth = true;
              this.searchForm.postDateEnd = new Date().Format('yyyy-MM-dd')
              this.searchForm.postDateStart = new Date(Date.parse(new Date()) - 30*24*60*60*1000).Format('yyyy-MM-dd')
              this.searchReport(1)
            }
          } else {
            this.comOptions = [];
          }
        })
        .catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: '确定1',
            customClass: 'alertFailure',
          });
          this.comOptions = [];
        });
    },
  },
  props: {
    removeTab: {
      type: Function,
    },
  },
};
</script>
